import * as React from "react";
import { Form, Row, Col, Input, Button, Icon, DatePicker, Select, Table, message, Modal, Spin } from 'antd';
const { confirm } = Modal;
const { Option } = Select;
const { Column } = Table;
import * as moment from 'moment';
import './index.scss';
import { FormComponentProps } from 'antd/lib/form/Form' //获取form表单的interface
import { ListGUID } from '../../config/ListGuid';
import Api from '../../config/api';
import { dynamicsService } from "../../../../../services/services";
import { Prompt, Link } from "react-router-dom";
import { isHavePermission, isHavePathPermission } from '../../utils/utils'
const layout = {
  labelCol: {
    span: 4,

  },
  wrapperCol: {
    offset: 1,
    span: 19,
  },
}

const phoneValidator = (rule: any, value: any, callback: any) => {
  if (!value) {
    callback('请输入！')
  }
  // 必须总是返回一个 callback，否则 validateFields 无法响应
  callback();
}


const tipData = [
  {
    field: '合同编号',
    content: '编号规则参考SEM<合同编号规则>第2条',
    remarks: '系统自动生成'
  },
  {
    field: '法务受理日',
    content: '合同的首次正式受理日',
    remarks: '必填'
  },
  {
    field: '法务最后回答日',
    content: '法务正式修改案或法务意见书的出具日',
    remarks: '必填'
  },
  {
    field: '合同名称',
    content: '合同标题（需与文书上合同名一致，请注意删除文字间的空格）',
    remarks: '必填'
  },
  {
    field: '关键词1',
    content: '应列出可供识别的信息，如房屋租赁地址',
    remarks: '选填'
  },
  {
    field: '关键词2',
    content: '如货物名称、工程名称等',
    remarks: '选填'
  },
  {
    field: '我方',
    content: '住化公司名称（缩写）',
    remarks: '必填'
  },
  {
    field: '相对方',
    content: '交易相对方公司全称；住化集团公司可用简称',
    remarks: '必填'
  },
  {
    field: '社内依赖者名',
    content: '该合同审查依赖担当',
    remarks: '必填'
  },
  {
    field: '所属公司',
    content: '社内依赖者所属公司系统自动带出（未带出的请手动输入）',
    remarks: '必填'
  },
  {
    field: '所属部门',
    content: '社内依赖者所属部门系统自动带出（未带出的请手动输入）',
    remarks: '必填'
  },
  {
    field: '语言',
    content: '合同采用的语言（如有多种请均填入，并将优先效力的语言放在首位，如中英）',
    remarks: '必填'
  },
  {
    field: '问题',
    content: '选项：“有”：有修改意见或有风险提示；“无”：无修改意见',
    remarks: '必填'
  },
  {
    field: '合同性质',
    content: '选项：合同相应的性质（择一）',
    remarks: '必填'
  },
  {
    field: '合同期限',
    content: '选项：一次性/自动延长/到期续签',
    remarks: '必填'
  },
  {
    field: '合同重要性',
    content: '重要/一般（如①基本交易合同②设备采购合同（100万元以上/年）③口钱合同④顾问合同⑤保密协议）',
    remarks: '必填'
  },
  {
    field: '合同修改性质',
    content: '选项：根据合同审核指南选取1项或多项',
    remarks: '必填'
  },
  {
    field: '资质',
    content: '选项：“有”：有符合合同业务的资质；“无”：不具备合同业务的资质或资质有瑕疵“无需资质”：合同业务无法定资质许可的强制性要求',
    remarks: '必填'
  },
  {
    field: '审核意见书',
    content: `选项：“有”：有出具审核意见书；“无”：未出具审核意见书`,
    remarks: '必填'
  },
  {
    field: '律师审查',
    content: '选项：有/无',
    remarks: '必填'
  },
  {
    field: '决裁编号',
    content: '同FL决裁编号',
    remarks: '系统自动生成'
  },
  {
    field: '文件保存',
    content: '法务审核版、审查意见书及资质等的存放地址',
    remarks: '系统自动生成'
  },
  {
    field: '其他',
    content: '备注信息，如合同未定稿的情形，如交涉中，被搁置，中止交涉等；如遇合同属于SEMW分公司，需写明哪家分公司',
    remarks: '选填'
  },
  {
    field: '审查担当',
    content: '选项默认为编号人（按照选择顺序确认一审、二审、三审）',
    remarks: '必填',
  }
]

// eslint-disable-next-line arrow-body-style
// 测试代码，调试API使用
class AddContractNo extends React.Component<any> {
  constructor(props: any) {
    super(props);
  }
  //提交按钮触发
  submit = async (e) => {
    
    if(e === '提交' || e === '作废') {
      if(this.state.currentForm &&
        this.state.currentForm.Title.indexOf('DUMY') === -1 &&
        (
          moment(this.state.currentForm.AcceptTime).format('YYYY') !== moment(this.state.form.date).format('YYYY') ||
          this.state.currentForm.Our !== this.state.form.we
        )
        ) {
          message.warning('提交失败，当前【受理日】与【我方】数据与合同编号信息不匹配，请重新检查或点击“生成编号”按钮来生成新的编号。')
          
          return
      }
    }
    await this.setState({
      variable: e == '作废' ? '废弃' : e == '提交' ? '有效' : '草稿'
    })
    if (e == '作废') {
      let array = await Api.getFiles(ListGUID.ContractLibRelativeUrl + '/' + this.state.form.file)
      if (array.length != 0) {
        message.warning(`存在附件,请先删除附件`, 2)
        return;
      }
    }
    if (e == '保存草稿') {
      //this.getSubmit()
      this.warning('保存草稿')
    } else {
      this.props.form.validateFields((err, values) => {
        if (!err) {
          //this.getSubmit()
          e == '提交' ? e = '保存' : e = e; // 提示语: 是否保存?
          this.warning(e)
        }
      });
    }

  };
  disabledDate = time => {
    if (this.state.JudgmentVariable != null) {
      if (this.state.form.contract.indexOf('DUMY') === -1) {
        var timeYear = time.get('year');  //当前年
        // 
        var currentYear = this.state.time; //今年
        return timeYear != currentYear;
      } else {
        
      }
    }
  };
  //初始化数据
  initialization = () => {
    let { form } = this.state;
    form = {
      
      submitted: true,
      // 法务受理日
      date: null,
      // 法务最后回答日
      date1: null,
      // 语言
      language: null,
      // 合同名称
      theContract: null,
      // 关键词1
      keywords1: null,
      // 关键词2
      keywords2: null,
      // 合同修改性质
      modification: [],
      // 相对方
      otherSide: null,
      // 社内依赖者名
      community: null,
      // 其他
      other: null,
      // 合同编号
      contract: '',
      // 决裁编号
      cutNumber: '',
      // 审查担当
      reviewOn: null,
      // 文件保存
      file: null,

      //下拉选择
      //问题
      problem: undefined,
      //性质
      nature: undefined,
      //期限
      term: undefined,
      //重要性
      importance: undefined,
      //我方
      we: undefined,
      //资质
      qualifications: '无',
      //律师审查
      examination: 1,
      //审查担当
      reviewOnxuan: [],
      //所属公司
      company: undefined,
      //所属部门
      department: undefined,
      //审查担当
      reviewOnxuans: undefined,
      AttObject: [],
      enclosurelist: [],
      //意见书
      proposal: '无',
    }
    this.setState({
      form,
      wedisabled: false,
      JudgmentVariable: null,
      JudgmentVariableID: null,
      DraftNo: null,
      discardID: null,
      time: null
    })
    this.props.form.setFieldsValue({
      contract: '',
      date: null,
      date1: null,
      theContract: null,
      text: undefined,
      otherSide: null,
    })
  };



  // 法务受理日
  onChange = (date, dateString) => {
    
    this.setState({
      form: {
        ...this.state.form,
        date: dateString
      }
    })
  }
  // 法务最后回答日
  onChange1 = (date, dateString) => {
    this.setState({
      form: {
        ...this.state.form,
        date1: dateString
      }
    })
  }
  state = {
    
    tipVisible: false,
    AuthorId: JSON.parse(sessionStorage.getItem('userInfo')).Id,
    AuthorName: JSON.parse(sessionStorage.getItem('userInfo')).Title,
    currentForm: null,
    loading: false,
    contractId: '',
    backPage: '', //返回的页面
    //表单数据对象
    form: {
      submitted: true,
      // 法务受理日
      date: null,
      // 法务最后回答日
      date1: null,
      // 语言
      language: null,
      // 合同名称
      theContract: null,
      // 关键词1
      keywords1: null,
      // 关键词2
      keywords2: null,
      // 合同修改性质
      modification: [],
      // 相对方
      otherSide: null,
      // 社内依赖者名
      community: null,
      // 其他
      other: null,
      // 合同编号
      contract: '',
      // 决裁编号
      cutNumber: '',
      // 审查担当
      reviewOn: null,
      // 文件保存
      file: null,

      //下拉选择
      //问题
      problem: undefined,
      //性质
      nature: undefined,
      //期限
      term: undefined,
      //重要性
      importance: undefined,
      //我方
      we: undefined,
      //资质
      qualifications: '无',
      //律师审查
      examination: 1,
      //审查担当
      reviewOnxuan: [],
      //所属公司
      company: undefined,
      //所属部门
      department: undefined,
      //审查担当
      reviewOnxuans: undefined,
      //上传文件
      AttObject: [],
      //附件名称
      enclosurelist: [],
      //意见书
      proposal: '无',

    },
    //问题
    problemList: [],
    //合同性质
    natureList: [],
    //合同期限
    termList: [],
    //合同重要性
    importanceList: [],
    //我方
    weList: [],
    //资质
    qualificationsList: ['有', '无', '无需资质'],
    //律师审查
    LawyerList: [],
    //所属公司
    companyList: ['SEM', 'SEMW', 'SEMX'],
    //所属部门
    departmentList: [],
    //审查担当
    personreviewList: [],
    //修改性质
    modificationList: [],
    //状态
    variable: '',
    //依赖者
    communityList: [],
    //变量
    JudgmentVariable: null,
    JudgmentVariableID: null,
    fujian: null,
    wedisabled: false,
    filelist: [],
    DraftNo: null,
    //草稿启用废弃编号id
    discardID: null,
    time: null
  }
  onBlur(e) {
    let paten = /^[A-Za-z]+$/g;
    
    
    if (!paten.test(this.state.form.we)) {
      message.warning('请输入字母', 2);
      setTimeout(() => {
        this.setState({
          form: {
            ...this.state.form,
            we: undefined,
          }
        })
        
        this.props.form.setFieldsValue({
          text: undefined,
        })
      }, 100)
      return;
    }
    
    this.props.form.setFieldsValue({
      text: this.state.form.we
    })
  }
  // 输入框改变赋值
  change(e, key) {
    if (key == 'we') {
      this.setState({
        form: {
          ...this.state.form,
          [key]: e.target.value.toUpperCase()
        }
      })
    } else {
      this.setState({
        form: {
          ...this.state.form,
          [key]: e.target.value
        }
      })
    }


  }

  allowClear(e, key) {
    const { value } = e.target;
    if (!value && e.type !== 'change') {
      // do something
      this.setState({
        form: {
          ...this.state.form,
          [key]: undefined,
          company: undefined,
          //所属部门
          department: undefined,
        }
      })
    } else {
      this.setState({
        form: {
          ...this.state.form,
          [key]: e.target.value
        }
      })
    }
  }


  loseFocus(e, key) {
    let array = JSON.parse(sessionStorage.getItem('AADUsers'));
    let size: any = []
    for (let index = 0; index < array.length; index++) {
      if (e.target.value == array[index].displayName) {
        size.push(array[index])
      }
    }

    if (size.length == 0) {
      this.setState({
        form: {
          ...this.state.form,
          [key]: e.target.value,
          company: undefined,
          //所属部门
          department: undefined,
        }
      })
    } else {
      this.setState({
        form: {
          ...this.state.form,
          [key]: size[0].displayName,
          company: size[0].companyName,
          //所属部门
          department: size[0].department,
        }
      })
    }




    // company: v.props.children[2],
    //所属部门
    // department: v.props.children[4],



  }




  // 下拉框改变赋值
  handleSelectChange(e, key) {
    this.setState({
      form: {
        ...this.state.form,
        [key]: e,
      }
    })
  }
  // 下拉框改变赋值
  handleSelectChanges(e, v, key) {
    var array = []
    var arrays = []
    v.forEach(element => {
      array.push(element.key)
      arrays.push(`${element.props.value}#${element.props.children}`)
    });
    
    this.setState({
      form: {
        ...this.state.form,
        reviewOn: array.join(","),
        reviewOnxuans: arrays.join(';'),
        [key]: e
      }
    })
  }
  // 下拉框改变赋值
  handleSelectChangess(e, v, key) {
    if (e != undefined) {
      this.setState({
        form: {
          ...this.state.form,
          [key]: e,
          company: v.props.children[2],
          //所属部门
          department: v.props.children[4],
        }
      })
    } else {
      this.setState({
        form: {
          ...this.state.form,
          [key]: e,
          company: undefined,
          //所属部门
          department: undefined,
        }
      })
    }

  }
  //提示框
  warning = (e = '保存') => {
    // 已经提交过
    if (!this.state.form.submitted) {
      // message.error('此合同编号已经提交,请勿重复操作')
      //提示框
      
      confirm({
        centered: true,
        title: '温馨提示',
        content: e === '作废' ? '是否作废？' : `此合同编号已经提交,是否更新数据？`,
        okText: '确认',
        cancelText: '取消',
        onOk: () => {
          this.getSubmit(e)
          // setTimeout(() => {
          //   this.initialization()
          // }, 500)

        }
      });

      return
    }
    
    confirm({
      centered: true,
      title: '温馨提示',
      content: `是否` + e + `?`,
      okText: '确认',
      cancelText: '取消',
      onOk: () => { this.getSubmit(e) }
    });
  };
  toOtherPage = (e) => {
    location.href = e
  }
  handleCancel = () => {
    this.setState({
      tipVisible: false
    })
  }
  //动态更新绑定数据
  public async componentDidMount() {
    isHavePathPermission();
    this.setButtonsEventHandlers();
    this.getTest();// 测试代码，调试API使用
    let title = this.props.location.state
    if (title != undefined) {
      

      this.getedit(title.id)
      this.setState({
        contractId: title.id,
        backPage: title.backPage
      })
    }
    this.setState({
      AuthorId: JSON.parse(sessionStorage.getItem('userInfo')).Id,
      AuthorName: JSON.parse(sessionStorage.getItem('userInfo')).Title
    })
    let token = await dynamicsService.getToken()
    

    // let getlist = JSON.parse(sessionStorage.getItem('AADUsers'));
    // 
    // // await dynamicsService.getusers(token.data.data)
    // this.setState({
    //   communityList: getlist
    // })
  }

  //编号 生成 我方+年+3位自增长序号 
  //   合同/{年度}/{公司别}/{合同编号} [{申请书序列号}]
  public render(): React.ReactElement {

    const { getFieldDecorator } = this.props.form;
    const prefixSelector =
      <Select style={{ width: 130 }}>
        {
          this.state.personreviewList.map(element => {
            return <Option value={element} key={element}>{element}</Option>
          })
        }
      </Select>

    return (
      <div className='box'>
        <Spin spinning={this.state.loading}>
        <div className='box_content'>
          <Prompt
            when={false}
            message={(location) =>
              "当前页面有未保存的内容,是否离开？"
            }
          />
          <Row align="middle" justify="end">
            <Col span={24}>
              <div className='flex'>
                <div className="heTong"></div>
                <div className='het'>合同编号 <span onClick={() => this.setState({tipVisible: true})}>(填写说明)</span></div>
              </div>
            </Col>
          </Row>
          <Row type="flex" justify="end">
            {
                isHavePermission('AddContractNo/tocontractversion') ? <Col span={1}><Button type="default" className="Button_4" onClick={() => { this.toOtherPage("#/AddContractVersion") }}>版本号</Button></Col> : null
              }
            {
                isHavePermission('AddContractNo/abandon') ? <Col span={1} offset={1}><Button type="default" className="Button_1" disabled={this.state.form.contract.indexOf('DUMY') !== -1  ? true : false} onClick={() => { this.submit("作废") }}>作废</Button></Col> : null
              }
            {
                isHavePermission('AddContractNo/submit') ? <Col span={1} offset={1}><Button type="primary" className="Button_2" onClick={() => { this.submit("提交") }}>提交</Button></Col> : null
              }
            {
                isHavePermission('AddContractNo/draft') ? <Col span={1} offset={1}><Button type="primary" className="Button_3" disabled={this.state.form.contract && this.state.form.contract.indexOf('DUMY') === -1  ? true : false} onClick={() => { this.submit("保存草稿") }}>草稿</Button></Col> : null
              }
            {
                isHavePermission('AddContractNo/close') ? <Col span={1} offset={1}><Button type="primary" onClick={this.shutDown}>关闭</Button></Col> : null
              }
              {
                this.state.contractId != '' ? <Col span={1} offset={1}> <Button type="primary" onClick={() => { this.props.history.push({ pathname: this.state.backPage, state: { isBack: 1 } }) }}>返回</Button> 
             
           </Col> : ''
              }
            
          </Row>
          <div className="top"></div>
          <Form {...layout} name='login' layout="inline">
            <Row type="flex" justify="space-between">
              <Col span={11}>
                <Form.Item label='合同编号' labelAlign="right">
                  {
                    getFieldDecorator('contract', {
                      rules: [
                        {
                          validator: phoneValidator,
                          required: true,
                        }
                      ],
                      initialValue: this.state.form.contract
                    })(<Input allowClear disabled placeholder="请输入" />)
                  }
                </Form.Item>
              </Col>
              <Col span={2}>
                <Form.Item>
                  {
                    isHavePermission('AddContractNo/createnum') ? <Button style={{marginLeft: '0px'}} type="primary" className="Button_3" onClick={this.generateNumber}>生成编号</Button> : null
                  }
                </Form.Item>
              </Col>
              <Col span={11} >
                <Form.Item label='语言' labelAlign="right">
                  <Input allowClear placeholder="请输入内容" value={this.state.form.language} onChange={(event) => { this.change(event, "language") }} />
                </Form.Item>
              </Col>
              <Col span={11}>
                <Form.Item label='法务受理日' labelAlign="right">
                  {
                    getFieldDecorator('date', {
                      rules: [
                        {
                          validator: phoneValidator,
                          required: true
                        }
                      ]
                      // disabledDate={this.disabledDate}
                    })(<DatePicker allowClear style={{ width: '100%' }} placeholder="请选择年份" onChange={this.onChange} format='YYYY/MM/DD'  />)
                  }

                </Form.Item>
              </Col>

              <Col span={11} >
                <Form.Item label='问题' labelAlign="right">
                  <Select
                    allowClear
                    placeholder="请选择"
                    value={this.state.form.problem}
                    onChange={(event) => { this.handleSelectChange(event, "problem") }}
                  >
                    {
                      this.state.problemList.map(element => {
                        return <Option value={element.ID} key={element.Title}>{element.Title}</Option>
                      })
                    }
                  </Select>
                </Form.Item>
              </Col>

              <Col span={11}>
                <Form.Item label='法务最后回答日' labelAlign="right">
                  {
                    getFieldDecorator('date1', {

                    })(<DatePicker allowClear style={{ width: '100%' }} placeholder="请选择年份" onChange={this.onChange1} format='YYYY/MM/DD' />)
                  }

                </Form.Item>
              </Col>

              <Col span={11} >
                <Form.Item label='合同性质' labelAlign="right">
                  <Select
                    allowClear
                    placeholder="请选择内容"
                    value={this.state.form.nature}
                    onChange={(event) => { this.handleSelectChange(event, "nature") }}
                  >
                    {
                      this.state.natureList.map(element => {
                        return <Option value={element.ID} key={element.ID}>{element.Title}</Option>
                      })
                    }
                  </Select>
                </Form.Item>
              </Col>

              <Col span={11}>
                <Form.Item label='合同名称' labelAlign="right" >
                  {
                    getFieldDecorator('theContract', {
                      rules: [
                        {
                          validator: phoneValidator,
                          required: true
                        }
                      ],
                      initialValue: this.state.form.theContract
                    })(<Input allowClear placeholder="请输入内容" onChange={(event) => { this.change(event, "theContract") }} />)
                  }
                </Form.Item>
              </Col>

              <Col span={11} >
                <Form.Item label='合同期限' labelAlign="right">
                  <Select
                    allowClear
                    placeholder="请选择内容"
                    value={this.state.form.term}
                    onChange={(event) => { this.handleSelectChange(event, "term") }}
                  >
                    {
                      this.state.termList.map(element => {
                        return <Option value={element.ID} key={element.ID}>{element.Title}</Option>
                      })
                    }
                  </Select>
                </Form.Item>
              </Col>

              <Col span={11}>
                <Form.Item label='关键词1' labelAlign="right">
                  <Input allowClear placeholder="请输入内容" value={this.state.form.keywords1} onChange={(event) => { this.change(event, "keywords1") }} />
                </Form.Item>
              </Col>


              <Col span={11} >
                <Form.Item label='合同重要性' labelAlign="right">
                  <Select
                    allowClear
                    placeholder="请选择内容"
                    value={this.state.form.importance}
                    onChange={(event) => { this.handleSelectChange(event, "importance") }}
                  >
                    {
                      this.state.importanceList.map(element => {
                        return <Option value={element.ID} key={element.ID}>{element.Title}</Option>
                      })
                    }
                  </Select>
                </Form.Item>
              </Col>

              <Col span={11}>
                <Form.Item label='关键词2' labelAlign="right">
                  <Input allowClear placeholder="请输入内容" value={this.state.form.keywords2} onChange={(event) => { this.change(event, "keywords2") }} />
                </Form.Item>
              </Col>

              <Col span={11} >
                <Form.Item label='合同修改性质' labelAlign="right">
                  <Select
                    allowClear
                    mode='multiple'
                    placeholder="请选择内容"
                    value={this.state.form.modification}
                    maxTagCount={4}
                    onChange={(event) => { this.handleSelectChange(event, "modification") }}
                  >
                    {
                      this.state.modificationList.map(element => {
                        return <Option value={element.Title} key={element.ID}>{element.Title}</Option>
                      })
                    }
                  </Select>
                </Form.Item>
              </Col>


              <Col span={11}>
                <Form.Item label='我方' labelAlign="right">
                  {
                    getFieldDecorator('text', {
                      rules: [
                        {
                          validator: phoneValidator,
                          required: true
                        }
                      ],
                      initialValue: this.state.form.we
                    })(
                      // <Input allowClear placeholder="请输入内容" style={{ textTransform: 'uppercase' }} onBlur={(event) => { this.onBlur(event) }} onChange={(event) => { this.change(event, "we") }} disabled={this.state.wedisabled} />
                      <Select
                        allowClear
                        onChange={(event) => { this.handleSelectChange(event, "we") }}
                        placeholder="请选择"
                      >
                        {
                          this.state.weList.map(element => {
                            return <Option value={element.Title} key={element.Title}>{element.Title}</Option>
                          })
                        }
                      </Select>

                    )
                  }
                </Form.Item>
              </Col>


              <Col span={11} >
                <Form.Item label='资质' labelAlign="right">
                  <Select
                    allowClear
                    placeholder="请选择"
                    value={this.state.form.qualifications}
                    onChange={(event) => { this.handleSelectChange(event, "qualifications") }}
                  >
                    {
                      this.state.qualificationsList.map(element => {
                        return <Option value={element} key={element}>{element}</Option>
                      })
                    }
                  </Select>
                </Form.Item>
              </Col>

              <Col span={11}>
                <Form.Item label='相对方' labelAlign="right">
                  {
                    getFieldDecorator('otherSide', {
                      rules: [
                        {
                          validator: phoneValidator,
                          required: true
                        }
                      ],
                      initialValue: this.state.form.otherSide
                    })(<Input allowClear placeholder="请输入内容" onChange={(event) => { this.change(event, "otherSide") }} />)
                  }
                </Form.Item>
              </Col>

              <Col span={11} >
                <Form.Item label='审核意见书' labelAlign="right">
                  <Select
                    allowClear
                    placeholder="请选择"
                    value={this.state.form.proposal}
                    onChange={(event) => { this.handleSelectChange(event, "proposal") }}
                  >
                    <Option value='有' >有</Option>
                    <Option value='无' >无</Option>
                  </Select>
                </Form.Item>
              </Col>


              <Col span={11}>
                <Form.Item label='社内依赖者名' labelAlign="right">
                  {/* <Select
                    allowClear
                    showSearch
                    placeholder="请选择"
                    value={this.state.form.community}
                    onChange={(event, value) => { this.handleSelectChangess(event, value, "community") }}
                    optionFilterProp="children"
                    filterOption={(input, option: any) => {
                      return (Array.isArray(option.props.children) ? option.props.children.join('') : option.props.children).toLowerCase().indexOf(input.toLowerCase()) >= 0
                    }}
                  >
                    {
                      this.state.communityList.map(element => {
                        return <Option value={element.displayName} key={element.displayName}>{element.displayName} 公司:{element.companyName} 部门:{element.department}</Option>
                      })
                    }
                  </Select> */}
                  <Input allowClear placeholder="请输入内容" value={this.state.form.community}
                    onChange={(event) => { this.allowClear(event, "community") }}
                    onBlur={(event) => { this.loseFocus(event, "community") }} />
                  {/* {
                    getFieldDecorator('community', {
                      rules: [
                        {
                          validator: phoneValidator,
                          required: false
                        }
                      ],
                      initialValue: this.state.form.community
                    })(<Input allowClear placeholder="请输入内容"
                      onChange={(event) => { this.allowClear(event, "keywords2") }}
                      onBlur={(event) => { this.loseFocus(event, "community") }} />)
                  } */}

                </Form.Item>
              </Col>

              <Col span={11} >
                <Form.Item label='律师审查' labelAlign="right">
                  <Select
                    allowClear
                    placeholder="请选择"
                    value={this.state.form.examination}
                    onChange={(event) => { this.handleSelectChange(event, "examination") }}
                  >
                    {
                      this.state.LawyerList.map(element => {
                        return <Option value={element.ID} key={element.ID}>{element.Title}</Option>
                      })
                    }
                  </Select>
                </Form.Item>
              </Col>
              <Col span={11}>
                <Form.Item label='所属公司' labelAlign="right">
                  <Input
                    allowClear
                    value={this.state.form.company}
                    placeholder="请输入内容" onChange={(event) => { this.change(event, "company") }}
                  >

                  </Input>
                </Form.Item>
              </Col>

              <Col span={11} >
                <Form.Item label='决裁编号' labelAlign="right">
                  <Input allowClear disabled value={this.state.form.cutNumber} placeholder='请输入' />
                </Form.Item>
              </Col>


              <Col span={11}>
                <Form.Item label='所属部门' labelAlign="right">
                  <Input
                    allowClear
                    value={this.state.form.department}
                    placeholder="请输入内容" onChange={(event) => { this.change(event, "department") }}
                  >

                  </Input>
                </Form.Item>
              </Col>

              <Col span={11} >
                <Form.Item label="审查担当">
                  <Input.Group compact>
                    <Select allowClear mode='multiple' placeholder="请选择" style={{ width: '35%' }} value={this.state.form.reviewOnxuan}
                      onChange={(event, value) => { this.handleSelectChanges(event, value, "reviewOnxuan") }} maxTagCount={1}>
                      {
                        this.state.personreviewList.map(element => {
                          return <Option value={element.ID} key={element.Title}>{element.Title}</Option>
                        })
                      }
                    </Select>
                    <Input allowClear style={{ width: '65%' }}
                      placeholder="请输入内容" disabled value={this.state.form.reviewOn} />
                  </Input.Group>
                </Form.Item>
              </Col>

              <Col span={11}>
                <Form.Item label='其他' labelAlign="right">
                  <Input allowClear placeholder="请输入内容" onChange={(event) => { this.change(event, "other") }} value={this.state.form.other} />
                </Form.Item>
              </Col>

              <Col span={11} >
                <Form.Item label='文件保存' labelAlign="right">

                  {/* <Input allowClear value={this.state.form.file} onClick={this.getFilds} readOnly /> */}
                  <Input allowClear value={this.state.form.file} onClick={this.getFilds} readOnly />
                  {
                    isHavePermission('AddContractNo/upload') ? <Input allowClear placeholder="附件" multiple value={this.state.fujian} id="fileUploadInput" type="file" name="myfile" style={{ display: "none", }} /> : null
                  }
                </Form.Item>
              </Col>





            </Row>

          </Form>
        </div>
        </Spin>
        <Modal
          title="填写说明"
          visible={this.state.tipVisible}
          width={'50%'}
          footer={false}
          onCancel={this.handleCancel}
          className="tipsModel"
        >
          <Table size="small" dataSource={tipData} bordered pagination={false} footer={() => <p>版本号：指主合同的补充协议、变更协议、续签协议等与主合同有关联的编号，在“-0”的基础上累加编号。为避免编错号码，在版本号“合同编号”处输入主合同“-0”前的编号并点击空白处后会显示主合同信息，主合同信息无误的点击”匹配“，生成版本号。</p>}>
              <Column title="字段" dataIndex="field" key="field" width='150px' render={(_: any, record:any) => (
                <span style={{color: '#333'}}>{record.field}</span>
              )} />
              <Column title="填写内容" dataIndex="content" key="content" />
              <Column title="备注" dataIndex="remarks" key="remarks" width='150px' align="center" render={(_: any, record:any) => (
                <span style={{color: record.remarks === '必填' ? 'red' : record.remarks === '系统自动生成' ? '#87d068' : 'initial'}}>{record.remarks}</span>
              )} />
          </Table>
        </Modal>
      </div>
    )

  }
  private setButtonsEventHandlers(): void {
    let fileUpload = document.getElementById('fileUploadInput');
    if (fileUpload) {
      fileUpload.addEventListener('change', () => {
        this.fileinputChange(fileUpload);
      });
    }
  }
  getFilds = () => {
    
    
    if (this.state.form.file) {
      // const filedom = document.getElementById('fileUploadInput');
      // filedom.click()
      // window.open(ListGUID.DocumentLink+ '?sourcedoc=' +this.state.form.file)
      // window.open(ListGUID.Domain + ListGUID.ContractLibRelativeUrl + '/ContractLib/' + this.state.form.file)
      
      // window.open(ListGUID.Domain + ListGUID.ContractLibRelativeUrl+'/'+ this.state.form.file)
      dynamicsService.UpdateListFileNames({dataid: this.state.currentForm.id, listguid: ListGUID.StandingBook, fileaddress: this.state.currentForm.FileAddress}).then(() => {
        if (isHavePermission('AddContractNo/todocumentlibrary')) {
          if(this.state.form.contract.indexOf('DUMY') === -1) {
            window.open(ListGUID.Domain + ListGUID.ContractLibRelativeUrl + '/' + this.state.form.file)
          } else {
            window.open(ListGUID.Domain + ListGUID.DumyLibRelativeUrl + '/' + this.state.form.file)
          }
          
        }
      })
      
      return;
    }
    message.warning('暂无上传路径', 2)
  }
  //循环
  getloop = async (item) => {
    var fileData = item;
    let fSize = fileData.size
    let fileName = fileData.name
    var maxSize = 20 * 1024 * 1024; //限制20M
    if (fSize > maxSize) {
      message.warning(`${fileName}文件内容太大，上传失败，请检查文件后重新上传!`, 2)
      return;
    }
    //判断空文件
    if (fSize == 0) {
      //空文件
      message.warning(`${fileName}的文件内容为空，请检查文件后重新上传!`, 2)
      return;
    }

    //判断文件名称合法
    if (fileName.indexOf('.') > -1 || fileName.indexOf('%') > -1 || fileName.indexOf('#') > -1 || fileName.indexOf('+') > -1) {
      //排除 .
      if (fileName.indexOf('.') > -1) {
        let firstCodePosition = fileName.indexOf('.');
        let lastCodePosition = fileName.lastIndexOf('.');
        if (firstCodePosition != lastCodePosition) {
          //位置不同，有多个 
          message.warning(`${fileName}文件名称包含特殊字符‘.’，不允许上传，请修改文件名称后重新上传`, 2)
          return;
        }
      }

      //排除 % # +
      if (fileName.indexOf('%') > -1 || fileName.indexOf('#') > -1 || fileName.indexOf('+') > -1) {
        message.warning(`${fileName}文件名称包含特殊字符‘%、#、+’，不允许上传，请修改文件名称后重新上传`, 2)
        return;
      }
    }

    //判断文件名称超长       
    if (fileName.length >= 44) {
      message.warning(`${fileName}文件名称超过40个字符，请修改文件名称后重新上传`, 2)
      return;
    }
    let array = await Api.getFiles(ListGUID.ContractLibRelativeUrl + '/' + this.state.form.file)
    if (array.length != 0) {
      for (let j = 0; j < array.length; j++) {
        if (fileName == array[j].Name) {
          message.warning(`${fileName}文件名已在申请中或文档中心已存在，请勿重复申请`, 2)
          return;
        }
      }
    }
    let url = ListGUID.ContractLibRelativeUrl + '/' + this.state.form.file
    let parme = Api._addfiles(fileData, url)
    if (parme) {
      var arrays = [];
      arrays.push(fileName)
      arrays = this.state.form.enclosurelist.concat(arrays)
      this.setState({
        form: {
          ...this.state.form,
          enclosurelist: arrays
        }
      })
      message.success(`${fileName}文件上传成功`, 2)
      
    }
  }
  //上传附件
  fileinputChange = async (event) => {
    for (let i = 0; i < event.files.length; i++) {
      this.getloop(event.files[i])
    }
  }
  //合同性质 合同期限 合同重要性 律师审查 审查担当  公司设置  问题 部门列表
  //访问list NaturcontractGUID,ContractperiodGUID,ContractimportanceGUID,LawyerreviewGUID,PersonGUID,CompanysettingsGUID,ProblemGUID,DepartmentlstGUID
  public async getTest() {

    var _that = this
    var param7 = {
      Guid: ListGUID.ReviewOn //审查担当
    };
    let Person = await Api._getModel(param7);
    var param = {
      Guid: ListGUID.ContractNature //合同性质
    };
    let Naturcontract = await Api._getModel(param);

    var param1 = {
      Guid: ListGUID.ContractPeriod //合同期限
    };
    let Contractperiod = await Api._getModel(param1);
    // _that.state.termList = Contractperiod

    var param2 = {
      Guid: ListGUID.ContractImportance //合同重要性
    };
    let Contractimportance = await Api._getModel(param2);
    //_that.state.importanceList = Contractimportance

    var param3 = {
      Guid: ListGUID.LawerReview //律师审查
    };
    let Lawyerreview = await Api._getModel(param3);
    // _that.state.LawyerList = Lawyerreview

    var param4 = {
      Guid: ListGUID.Companies // 公司设置
    };
    let Companysettings = await Api._getModel(param4);
    // let Companysettings = JSON.parse(sessionStorage.getItem('userDataPer')).PermissionCompany
    // _that.state.weList = Companysettings

    var param5 = {
      Guid: ListGUID.Question // 问题
    };
    let Problem = await Api._getModel(param5);
    // _that.state.problemList = Problem

    var param6 = {
      Guid: ListGUID.Departments //部门列表
    };
    let Departmentlst = await Api._getModel(param6);

    var param7 = {
      Guid: ListGUID.ContractReviseNature //修改性质
    };
    let NatureContracts = await Api._getModel(param7);
    const userList = JSON.parse(localStorage.getItem('usersList'));
    Person = !this.state.contractId ? Person.filter(i => !i.Title.includes('-历史')) : Person
    Person.forEach(async item => {
      // let informationid = await Api.GetUserById(item.ReviewUserId)
      let informationid = userList.filter(i => i.id === item.ReviewUserId)
      if (informationid && informationid.length > 0) {
        item.Title = informationid.Title
      }

      return
    });
    setTimeout(() => {
      this.setState({
        natureList: Naturcontract,
        termList: Contractperiod,
        importanceList: Contractimportance,
        LawyerList: Lawyerreview,
        weList: Companysettings.filter(i => !i.Title.includes('-历史')),
        problemList: Problem,
        personreviewList: Person,
        departmentList: Departmentlst,
        modificationList: NatureContracts
      }, () => {
        if(!this.state.currentForm) {
          this.getcurrentUser()
        }
        
      })
    }, 300);
    // _that.state.problemList = Departmentlst
  }
  //默认登陆人
  public async getcurrentUser() {
    
    let { form } = this.state;
    //获取当前登录人
    let Loggedby = await Api._getcurrentUser();
    this.state.personreviewList.forEach(element => {
      if (Loggedby.Id === element.ReviewUserId) {
        form.reviewOnxuan = []
        form.reviewOnxuan.push(element.Id)
        form.reviewOn = element.Title
        form.reviewOnxuans = `${element.Id}#${element.Title}`
      }
    });
    this.setState({
      form
    })
    

  }
  //获取 title
  Ergodicvalue(array, id) {
    var value = null;
    for (var i = 0; i < array.length; i++) {
      if (array[i].ID == id) {
        value = array[i].Title;
      }
    }
    return value;
  }
  //importanceList  合同重要性   natureList 合同性质 problemList 问题 LawyerList 律师审查 termList 合同期限
  //提交合同 草稿 作废
  public async getSubmit(e) {
    
    

    if (this.state.currentForm) {
      // if(this.state.currentForm.Title) {
      //   this.AddData()
      // } else {
      //   this.UpdateData(this.state.currentForm.ItemId)
      // }
      this.UpdateData(this.state.currentForm.ItemId)
    } else {
      if (this.state.variable === '草稿') {
        this.AddData()
      }
    }



    // 
    // var date = new Date
    // var year = date.getFullYear();
    // // var param = {
    // //   Guid: ListGUID.StandingBook, //台账
    // //   Filter: `Title eq '${this.state.form.contract}'`
    // // };
    // // var Persons = await Api._getModel(param);
    // 
    // if (this.state.currentForm) {
    //   //  添加新合同
    //   var pa = {
    //     Guid: ListGUID.StandingBook,  //变更申请
    //     ItemId: this.state.currentForm.ItemId,
    //     Obj: {
    //       Title: this.state.form.contract, //合同编号
    //       AcceptTime: this.state.form.date == null ? null : this.state.form.date,//法务受理日
    //       Language: this.state.form.language,//语言
    //       Problem: this.state.form.problem,//问题id
    //       Contractualproblems: this.Ergodicvalue(this.state.problemList, this.state.form.problem),//问题
    //       LastAnswerTime: this.state.form.date1 == null ? null : this.state.form.date1,//法务最后回答
    //       ContractNatureID: this.state.form.nature,//合同性质id
    //       ContractNature: this.Ergodicvalue(this.state.natureList, this.state.form.nature),//合同性质
    //       ContractName: this.state.form.theContract,//合同名称
    //       ContractDeadlineID: this.state.form.term,//合同期限id
    //       ContractDeadline: this.Ergodicvalue(this.state.termList, this.state.form.term),//合同期限
    //       Keyword1: this.state.form.keywords1,//关键1
    //       ContractSignificanceID: this.state.form.importance,//合同重要性id
    //       ContractSignificance: this.Ergodicvalue(this.state.importanceList, this.state.form.importance),//合同重要性
    //       Keyword2: this.state.form.keywords2,//关键2
    //       ContactEditNature: this.state.form.modification.length > 0 ? this.state.form.modification.join(';') : '',//合同修改性质
    //       Our: this.state.form.we, //我方
    //       Qualifications: this.state.form.qualifications,//资质
    //       Counterparty: this.state.form.otherSide,//相对方
    //       LawyerReviewID: this.state.form.examination,//律师审查id
    //       ContractLawyerReview: this.Ergodicvalue(this.state.LawyerList, this.state.form.examination),//律师审查
    //       RelierName: this.state.form.community,//社内依赖者
    //       BelongsCompany: this.state.form.company,//所属公司
    //       ReviewOnID: this.state.form.reviewOnxuans,//审查担当
    //       BelongsDepartment: this.state.form.department,//所属部门
    //       FileAddress: this.state.form.file,//文件保存路径
    //       Other: this.state.form.other,//其它 
    //       HasReviewOpinion: this.state.form.proposal,//申请书
    //       // 有效、草稿、废弃
    //       ContractStatus: this.state.variable,//合同状态
    //       AcceptYear: this.state.form.date == null ? null : Number(this.state.form.date.substring(0, 4)),//受理日年份
    //       //流水号
    //       SerialNum: this.state.form.contract == '' || this.state.form.contract == null ? null : Number(this.state.form.contract.substring(0, this.state.form.contract.lastIndexOf('-')).substr(-3)),
    //       VersionNum: 0,
    //       Names: this.state.form.enclosurelist.length == 0 ? null : this.state.form.enclosurelist.join(';')
    //       // AttObject:this.state.form.AttObject
    //     }
    //   };
    //   
    //   if (this.state.JudgmentVariable == '废弃') {
    //     if (this.state.variable == '草稿') {
    //       let params: any = [
    //         {
    //           logic: "and",
    //           where: [
    //             {
    //               key: 'ContractStatus',
    //               filterType: "Eq",
    //               value: '草稿'
    //             },
    //             {
    //               key: 'AcceptYear',
    //               filterType: "Eq",
    //               value: Number(year)
    //             }
    //           ]
    //         }
    //       ];
    //       let data = await Api._getPaged2({ Guid: ListGUID.StandingBook, PageSize: 100000, PageIndex: 1, FilterL: params })
    //       let Persons = data.data;
    //       // var param = {
    //       //   Guid: ListGUID.StandingBook, //台账
    //       //   Filter: `ContractStatus eq '草稿' and  AcceptYear eq '${Number(year)}' `
    //       // };
    //       // let Persons = await Api._getModel(param);
    //       if (Persons.length != 0) {
    //         let array = []
    //         Persons.forEach(element => {
    //           array.push({
    //             Title: Number(element.Title.substr(-3)),
    //             ID: element.ItemId
    //           })
    //         });
    //         array.sort(function (a, b) {
    //           return a.Title - b.Title  //正序
    //         })
    //         pa.Obj.Title = 'DUMY' + Number(year) + this.prefixZero(Number(array[array.length - 1].Title) + 1, 3)
    //         pa.Obj.AcceptYear = Number(year)
    //       } else {
    //         pa.Obj.Title = 'DUMY' + Number(year) + "001"
    //         pa.Obj.AcceptYear = Number(year)
    //       }
    //     }
    //     
    //     let parm = {
    //       Guid: pa.Guid,
    //       ItemId: Number(this.state.JudgmentVariableID),
    //       Obj: pa.Obj
    //     }
    //     var UPdeta = await Api._updateData(parm)
    //     parm.Obj['ItemId'] = this.state.currentForm.ItemId;
    //     await dynamicsService.UpdateContract(parm.Obj)
    //     // this.initialization()
    //     return;
    //   } else if (this.state.JudgmentVariable == '草稿') {
    //     if (this.state.variable == '草稿') {
    //       pa.Obj.Title = this.state.DraftNo
    //       pa.Obj.AcceptYear = Number(year)
    //     }
    //     let parm = {
    //       Guid: pa.Guid,
    //       ItemId: Number(this.state.JudgmentVariableID),
    //       Obj: pa.Obj
    //     }
    //     
    //     var UPdeta = await Api._updateData(parm)
    //     parm.Obj['ItemId'] = Number(this.state.JudgmentVariableID)
    //     await dynamicsService.UpdateContract(parm.Obj)
    //     //草稿启用废弃编号 删除废弃记录
    //     if (this.state.DraftNo != null) {
    //       var params = {
    //         ListName: "StandingBook",//List表名
    //         ItemId: this.state.discardID,//要删除的List item的id
    //       };
    //       
    //       var data = await Api._deleteData(params);
    //       
    //     }
    //     // this.initialization()
    //     return;
    //   }
    //   if (this.state.variable == '草稿') {
    //     let params: any = [
    //       {
    //         logic: "and",
    //         where: [
    //           {
    //             key: 'ContractStatus',
    //             filterType: "Eq",
    //             value: '草稿'
    //           },
    //           {
    //             key: 'AcceptYear',
    //             filterType: "Eq",
    //             value: Number(year)
    //           }
    //         ]
    //       }
    //     ];
    //     let data = await Api._getPaged2({ Guid: ListGUID.StandingBook, PageSize: 100000, PageIndex: 1, FilterL: params })
    //     let Persons = data.data;
    //     // var param = {
    //     //   Guid: ListGUID.StandingBook, //台账
    //     //   Filter: `ContractStatus eq '草稿' and  AcceptYear eq '${Number(year)}' `
    //     // };
    //     // let Persons = await Api._getModel(param);
    //     if (Persons.length != 0) {
    //       let array = []
    //       Persons.forEach(element => {
    //         array.push({
    //           Title: Number(element.Title.substr(-3)),
    //           ID: element.ItemId
    //         })
    //       });
    //       array.sort(function (a, b) {
    //         return a.Title - b.Title  //正序
    //       })
    //       pa.Obj.Title = 'DUMY' + Number(year) + this.prefixZero(Number(array[array.length - 1].Title) + 1, 3)
    //       pa.Obj.AcceptYear = Number(year)
    //     } else {
    //       pa.Obj.Title = 'DUMY' + Number(year) + "001"
    //       pa.Obj.AcceptYear = Number(year)
    //     }
    //   }
    //   //废弃编号启用
    //   var UPdeta = await Api._updateData(pa)
    //   
    //   pa.Obj['ItemId'] = Number(this.state.JudgmentVariableID)
    //   await dynamicsService.UpdateContract(pa.Obj)
    //   // this.initialization()
    //   this.state.form.submitted = false
    //   // 
    //   // 
    // } else {
    //   //未生成编号 草稿
    //   var content = {
    //     Guid: ListGUID.StandingBook,  //变更申请
    //     Obj: {
    //       Title: this.state.form.contract, //合同编号
    //       AcceptTime: this.state.form.date == null ? null : this.state.form.date,//法务受理日
    //       Language: this.state.form.language,//语言
    //       Problem: this.state.form.problem,//问题
    //       Contractualproblems: this.Ergodicvalue(this.state.problemList, this.state.form.problem),//问题
    //       LastAnswerTime: this.state.form.date1 == null ? null : this.state.form.date1,//法务最后回答
    //       ContractNatureID: this.state.form.nature,//合同性质
    //       ContractNature: this.Ergodicvalue(this.state.natureList, this.state.form.nature),//合同性质
    //       ContractName: this.state.form.theContract,//合同名称
    //       ContractDeadlineID: this.state.form.term,//合同期限
    //       ContractDeadline: this.Ergodicvalue(this.state.termList, this.state.form.term),//合同期限
    //       Keyword1: this.state.form.keywords1,//关键1
    //       ContractSignificanceID: this.state.form.importance,//合同重要性
    //       ContractSignificance: this.Ergodicvalue(this.state.importanceList, this.state.form.importance),//合同重要性
    //       Keyword2: this.state.form.keywords2,//关键2
    //       ContactEditNature: this.state.form.modification.length > 0 ? this.state.form.modification.join(';') : '',//合同修改性质
    //       Our: this.state.form.we, //我方
    //       Qualifications: this.state.form.qualifications,//资质
    //       Counterparty: this.state.form.otherSide,//相对方
    //       LawyerReviewID: this.state.form.examination,//律师审查
    //       RelierName: this.state.form.community,//社内依赖者
    //       BelongsCompany: this.state.form.company,//所属公司
    //       ReviewOnID: this.state.form.reviewOnxuans,//审查担当id
    //       ContractLawyerReview: this.Ergodicvalue(this.state.LawyerList, this.state.form.examination),//律师审查
    //       BelongsDepartment: this.state.form.department,//所属部门
    //       FileAddress: this.state.form.file,//文件保存路径
    //       Other: this.state.form.other,//其它 
    //       HasReviewOpinion: this.state.form.proposal,//申请书
    //       // 有效、草稿、废弃
    //       ContractStatus: this.state.variable,//合同状态
    //       AcceptYear: this.state.form.date == null ? null : Number(this.state.form.date.substring(0, 4)),//受理日年份
    //       //流水号
    //       SerialNum: this.state.form.contract == '' || this.state.form.contract == null ? null : Number(this.state.form.contract.substring(0, this.state.form.contract.lastIndexOf('-')).substr(-3)),
    //       VersionNum: 0,
    //       Names: this.state.form.enclosurelist.length == 0 ? null : this.state.form.enclosurelist.join(';')
    //       // AttObject:this.state.form.AttObject
    //     }
    //   };
    //   
    //   if (this.state.JudgmentVariable == '草稿') {
    //     if (this.state.variable == '草稿') {
    //       content.Obj.Title = this.state.DraftNo
    //       content.Obj.AcceptYear = Number(year)
    //     }
    //     let parm = {
    //       Guid: content.Guid,
    //       ItemId: Number(this.state.JudgmentVariableID),
    //       Obj: content.Obj
    //     }
    //     var UPdeta = await Api._updateData(parm)
    //     parm.Obj['ItemId'] = Number(this.state.JudgmentVariableID);
    //     await dynamicsService.UpdateContract(parm.Obj)
    //     // this.initialization()
    //     return;
    //   }
    //   if (this.state.variable == '草稿') {
    //     let params: any = [
    //       {
    //         logic: "and",
    //         where: [
    //           {
    //             key: 'ContractStatus',
    //             filterType: "Eq",
    //             value: '草稿'
    //           },
    //           {
    //             key: 'AcceptYear',
    //             filterType: "Eq",
    //             value: Number(year)
    //           }
    //         ]
    //       }
    //     ];
    //     let data = await Api._getPaged2({ Guid: ListGUID.StandingBook, PageSize: 100000, PageIndex: 1, FilterL: params })
    //     let Persons = data.data;
    //     // var param = {
    //     //   Guid: ListGUID.StandingBook, //台账
    //     //   Filter: `ContractStatus eq '草稿'  and  AcceptYear eq '${Number(year)}'`
    //     // };
    //     // let Persons = await Api._getModel(param);
    //     if (Persons.length != 0) {
    //       let array = []
    //       Persons.forEach(element => {
    //         array.push({
    //           Title: Number(element.Title.substr(-3)),
    //           ID: element.ItemId
    //         })
    //       });
    //       array.sort(function (a, b) {
    //         return a.Title - b.Title  //正序
    //       })
    //       content.Obj.Title = 'DUMY' + Number(year) + this.prefixZero(Number(array[array.length - 1].Title) + 1, 3)
    //       content.Obj.AcceptYear = Number(year)
    //     } else {
    //       content.Obj.Title = 'DUMY' + Number(year) + "001"
    //       content.Obj.AcceptYear = Number(year)
    //     }
    //     
    //     let result = await Api._saveaddDataGuid(content);
    //     content.Obj['AuthorId'] = this.state.AuthorId;
    //     content.Obj['AuthorName'] = this.state.AuthorName;
    //     content.Obj['ItemId'] = result.data.ID;
    //     let newForm = await dynamicsService.AddContract(content.Obj)
    //     this.setState({
    //       currentForm: content.Obj
    //     })
    //     // Api.getChangeLog('合同台账')
    //     // this.initialization()
    //   }
    // }

  }
  // 更新数据
  UpdateData = async (id) => {
    
    this.setState({
      loading: true
    })
    let parm = {
      Guid: ListGUID.StandingBook,
      ItemId: id,
      Obj: {
        Title: this.state.form.contract, //合同编号
        AcceptTime: this.state.form.date == null ? null : this.state.form.date,//法务受理日
        Language: this.state.form.language,//语言
        Problem: this.state.form.problem,//问题id
        Contractualproblems: this.Ergodicvalue(this.state.problemList, this.state.form.problem),//问题
        LastAnswerTime: this.state.form.date1 == null ? null : this.state.form.date1,//法务最后回答
        ContractNatureID: this.state.form.nature,//合同性质id
        ContractNature: this.Ergodicvalue(this.state.natureList, this.state.form.nature),//合同性质
        ContractName: this.state.form.theContract,//合同名称
        ContractDeadlineID: this.state.form.term,//合同期限id
        ContractDeadline: this.Ergodicvalue(this.state.termList, this.state.form.term),//合同期限
        Keyword1: this.state.form.keywords1,//关键1
        ContractSignificanceID: this.state.form.importance,//合同重要性id
        ContractSignificance: this.Ergodicvalue(this.state.importanceList, this.state.form.importance),//合同重要性
        Keyword2: this.state.form.keywords2,//关键2
        ContactEditNature: this.state.form.modification && this.state.form.modification.length > 0 ? this.state.form.modification.join(';') : '',//合同修改性质
        Our: this.state.form.we, //我方
        Qualifications: this.state.form.qualifications,//资质
        Counterparty: this.state.form.otherSide,//相对方
        LawyerReviewID: this.state.form.examination,//律师审查id
        ContractLawyerReview: this.Ergodicvalue(this.state.LawyerList, this.state.form.examination),//律师审查
        RelierName: this.state.form.community,//社内依赖者
        BelongsCompany: this.state.form.company,//所属公司
        ReviewOnID: this.state.form.reviewOnxuans,//审查担当
        BelongsDepartment: this.state.form.department,//所属部门
        Other: this.state.form.other,//其它 
        HasReviewOpinion: this.state.form.proposal,//申请书
        // 有效、草稿、废弃
        ContractStatus: this.state.variable || '有效',//合同状态
        AcceptYear: this.state.form.date == null ? null : Number(this.state.form.date.substring(0, 4)),//受理日年份
        //流水号
        SerialNum: this.state.form.contract == '' || this.state.form.contract == null ? null : Number(this.state.form.contract.substring(0, this.state.form.contract.lastIndexOf('-')).substr(-3)),
        VersionNum: 0,
        // Names: this.state.form.enclosurelist && this.state.form.enclosurelist.length == 0 ? null : this.state.form.enclosurelist.join(';'),
        AuthorId: this.state.AuthorId,
        RuleNumber: this.state.form.cutNumber || ''
      }
    }
    // await Api._updateData(parm)
    parm.Obj['AuthorName'] = this.state.AuthorName;
    parm.Obj['ItemId'] = id;
    let response = await dynamicsService.UpdateContract(parm.Obj)
    if(response.code === 200) {
      let reviewOnxuan = []
    let reviewOn = []
    if (response.data.ReviewOnID) {
      if (response.data.ReviewOnID.indexOf(';') != -1) {
        let arrays = response.data.ReviewOnID.split(';')
        for (let i = 0; arrays.length > i; i++) {
          reviewOnxuan.push(Number(arrays[i].split('#')[0]))
          reviewOn.push(arrays[i].split('#')[1])
        }
      } else {
        reviewOnxuan.push(Number(response.data.ReviewOnID.split('#')[0]))
        reviewOn.push(response.data.ReviewOnID.split('#')[1])
      }
    }
    let form = {
        contract: response.data.Title, //合同编号
        date: response.data.AcceptTime == null ? null : moment(response.data.AcceptTime).format('YYYY/MM/DD'),//法务受理日
        language: response.data.Language,//语言　　　
        problem: response.data.Problem,//问题
        date1: response.data.LastAnswerTime == null ? null : moment(response.data.LastAnswerTime).format('YYYY/MM/DD'),//法务最后回答
        nature: response.data.ContractNatureID,//合同性质
        theContract: response.data.ContractName,//合同名称
        term: response.data.ContractDeadlineID,//合同期限
        keywords1: response.data.Keyword1,//关键1
        importance: response.data.ContractSignificanceID,//合同重要性
        keywords2: response.data.Keyword2,//关键2
        modification: !response.data.ContactEditNature ? [] : response.data.ContactEditNature.split(';'),//合同修改性质
        we: response.data.Our, //我方
        qualifications: response.data.Qualifications || '无',//资质
        otherSide: response.data.Counterparty,//相对方
        examination: response.data.LawyerReviewID  || 1,//律师审查 
        community: response.data.RelierName,//社内依赖者
        company: response.data.BelongsCompany,//所属公司
        reviewOnxuans: response.data.ReviewOnID,//审查担当
        department: response.data.BelongsDepartment,//所属部门
        file: response.data.FileAddress,//文件保存路径
        other: response.data.Other,//其它
        proposal: response.data.HasReviewOpinion || '无',//申请书 
        reviewOnxuan: reviewOnxuan,
        reviewOn: reviewOn,
        enclosurelist: response.data.Names == null ? [] : response.data.Names.split(';'),
        cutNumber: response.data.RuleNumber
    }
    this.props.form.setFieldsValue({
      contract: response.data.Title
    })
    this.setState({
      currentForm: response.data
    })
    if(!response.title.includes('DUMY')) {
      this.setState({
        form: form
      })
    }
    } else {
      message.warning(response.msg)
    }
    
    this.setState({
      loading: false
    })
  }
  // 新增数据
  AddData = async () => {
    this.setState({
      loading: true
    })
    let parm = {
      Guid: ListGUID.StandingBook,
      Obj: {
        // Title: this.state.form.contract, //合同编号
        AcceptTime: this.state.form.date == null ? null : this.state.form.date,//法务受理日
        Language: this.state.form.language,//语言
        Problem: this.state.form.problem,//问题id
        Contractualproblems: this.Ergodicvalue(this.state.problemList, this.state.form.problem),//问题
        LastAnswerTime: this.state.form.date1 == null ? null : this.state.form.date1,//法务最后回答
        ContractNatureID: this.state.form.nature,//合同性质id
        ContractNature: this.Ergodicvalue(this.state.natureList, this.state.form.nature),//合同性质
        ContractName: this.state.form.theContract,//合同名称
        ContractDeadlineID: this.state.form.term,//合同期限id
        ContractDeadline: this.Ergodicvalue(this.state.termList, this.state.form.term),//合同期限
        Keyword1: this.state.form.keywords1,//关键1
        ContractSignificanceID: this.state.form.importance,//合同重要性id
        ContractSignificance: this.Ergodicvalue(this.state.importanceList, this.state.form.importance),//合同重要性
        Keyword2: this.state.form.keywords2,//关键2
        ContactEditNature: this.state.form.modification && this.state.form.modification.length > 0 ? this.state.form.modification.join(';') : '',//合同修改性质
        Our: this.state.form.we, //我方
        Qualifications: this.state.form.qualifications,//资质
        Counterparty: this.state.form.otherSide,//相对方
        LawyerReviewID: this.state.form.examination,//律师审查id
        ContractLawyerReview: this.Ergodicvalue(this.state.LawyerList, this.state.form.examination),//律师审查
        RelierName: this.state.form.community,//社内依赖者
        BelongsCompany: this.state.form.company,//所属公司
        ReviewOnID: this.state.form.reviewOnxuans,//审查担当
        BelongsDepartment: this.state.form.department,//所属部门
        Other: this.state.form.other,//其它 
        HasReviewOpinion: this.state.form.proposal,//申请书
        // 有效、草稿、废弃
        ContractStatus: this.state.variable || '有效',//合同状态
        AcceptYear: this.state.form.date == null ? null : Number(this.state.form.date.substring(0, 4)),//受理日年份
        //流水号
        SerialNum: this.state.form.contract == '' || this.state.form.contract == null ? null : Number(this.state.form.contract.substring(0, this.state.form.contract.lastIndexOf('-')).substr(-3)),
        VersionNum: 0,
        // Names:  this.state.form.enclosurelist && this.state.form.enclosurelist.length == 0 ? null : this.state.form.enclosurelist.join(';'),
      }
    }
    parm.Obj['AuthorId'] = this.state.AuthorId;
    parm.Obj['AuthorName'] = this.state.AuthorName;
    let response = await dynamicsService.AddContract(parm.Obj)

    
    if (response.code === 200) {
      let reviewOnxuan = []
    let reviewOn = []
    if (response.data && response.data.ReviewOnID) {
      if (response.data.ReviewOnID.indexOf(';') != -1) {
        let arrays = response.data.ReviewOnID.split(';')
        for (let i = 0; arrays.length > i; i++) {
          reviewOnxuan.push(Number(arrays[i].split('#')[0]))
          reviewOn.push(arrays[i].split('#')[1])
        }
      } else {
        reviewOnxuan.push(Number(response.data.ReviewOnID.split('#')[0]))
        reviewOn.push(response.data.ReviewOnID.split('#')[1])
      }
    }
    
    let form = {
        contract: response.data.Title, //合同编号
        date: response.data.AcceptTime == null ? null : moment(response.data.AcceptTime).format('YYYY/MM/DD'),//法务受理日
        language: response.data.Language,//语言
        problem: response.data.Problem,//问题
        date1: response.data.LastAnswerTime == null ? null : moment(response.data.LastAnswerTime).format('YYYY/MM/DD'),//法务最后回答
        nature: response.data.ContractNatureID,//合同性质
        theContract: response.data.ContractName,//合同名称
        term: response.data.ContractDeadlineID,//合同期限
        keywords1: response.data.Keyword1,//关键1
        importance: response.data.ContractSignificanceID,//合同重要性
        keywords2: response.data.Keyword2,//关键2
        modification: !response.data.ContactEditNature ? [] : response.data.ContactEditNature.split(';'),//合同修改性质
        we: response.data.Our, //我方
        qualifications: response.data.Qualifications  || '无',//资质
        otherSide: response.data.Counterparty,//相对方
        examination: response.data.LawyerReviewID || 1,//律师审查 
        community: response.data.RelierName,//社内依赖者
        company: response.data.BelongsCompany,//所属公司
        reviewOnxuans: response.data.ReviewOnID,//审查担当
        department: response.data.BelongsDepartment,//所属部门
        file: response.data.FileAddress,//文件保存路径
        other: response.data.Other,//其它
        proposal: response.data.HasReviewOpinion  || '无',//申请书 
        reviewOnxuan: reviewOnxuan,
        reviewOn: reviewOn,
        enclosurelist: response.data.Names == null ? [] : response.data.Names.split(';'),
        cutNumber: response.data.RuleNumber
    }
      this.setState({
        form: form,
        JudgmentVariable: this.state.JudgmentVariableID != null ? this.state.JudgmentVariable : '有效',
        loading: false
      })
      this.props.form.setFieldsValue({
        contract: response.data.Title
      })
      this.setState({
        currentForm: response.data
      })
    } else {
      message.warning(response.msg);
      this.setState({
        loading: false
      })
    }

  }
  //生成编号
  private generateNumber = async (e) => {
      
        this.setState({
          variable: '有效'
        }, () => {
          e.preventDefault();
          this.props.form.validateFields(['data', 'otherSide', 'text', 'theContract'], async (err, values) => {
            if (!err) {
              // this.getcurrentUser()
              
              if (this.state.currentForm) {
                if(!this.state.currentForm.Title.includes('DUMY')) {
                  this.setState({
                    currentForm: {
                      ...this.state.currentForm,
                      Title: ''
                    }
                    
                  })
                  let { form } = this.state;
                  //获取当前登录人
                  let Loggedby = await Api._getcurrentUser();
                  this.state.personreviewList.forEach(element => {
                    if (Loggedby.Id === element.ReviewUserId) {
                      form.reviewOnxuan = []
                      form.reviewOnxuan.push(element.Id)
                      form.reviewOn = element.Title
                      form.reviewOnxuans = `${element.Id}#${element.Title}`
                    }
                  });
                  this.setState({
                    form
                  }, () => {
                    this.AddData()
                  })
                  
                } else {
                  this.UpdateData(this.state.currentForm.ItemId)
                }
      
              } else {
                this.AddData()
              }
              //获取废弃
              // var param = {
              //   Guid: ListGUID.StandingBook, //台账
              //   Filter: `Our eq '${this.state.form.we}' and  AcceptYear eq '${Number(this.state.form.date.substring(0, 4))}' and  ContractStatus eq '废弃' and VersionNum eq '0'`
              // };
              // var param = [
              //   {
              //     logic: "and",
              //     where: [
              //       {
              //         key: 'Our',
              //         filterType: "Eq",
              //         value: this.state.form.we
              //       },
              //       {
              //         key: 'AcceptYear',
              //         filterType: "Eq",
              //         value: this.state.form.date.substring(0, 4)
              //       },
              //       {
              //         key: 'ContractStatus',
              //         filterType: "Eq",
              //         value: '废弃'
              //       },
              //       {
              //         key: 'VersionNum',
              //         filterType: "Eq",
              //         value: '0'
              //       }
              //     ]
              //   }
              // ]
              // // let Persons = await Api._getModel(param);
              // let data1 = await Api._getPaged2({ Guid: ListGUID.StandingBook, PageSize: 100000, PageIndex: 1, FilterL: param })
              // let Persons = data1.data;
              // // if(this.state.currentForm && this.state.currentForm.)
              // if (Persons.length != 0) {
              //   let array = []
              //   Persons.forEach(element => {
              //     array.push({
              //       Titles: element.Title,
              //       Title: Number(element.Title.substring(0, element.Title.lastIndexOf('-')).substr(-3)),
              //       ID: element.ItemId
              //     })
              //   });
              //   array.sort(function (a, b) {
              //     return a.Title - b.Title  //正序
              //   })
              //   //获取废弃的编号
              //   let { form } = this.state;
              //   form.contract = array[0].Titles;
              //   this.props.form.setFieldsValue({
              //     contract: array[0].Titles
              //   });
              //   setTimeout(() => {
              //     form.file = this.state.form.date.substring(0, 4) + '/' + this.state.form.we + '/' + this.state.form.contract + '/';
              //     form.examination = 1
              //     form.proposal = '无'
              //     this.Folder(this.state.form.we, this.state.form.date.substring(0, 4), this.state.form.contract)
              //     this.setState({
              //       form,
              //       JudgmentVariableID: this.state.JudgmentVariableID != null ? this.state.JudgmentVariableID : array[0].ID,
              //       JudgmentVariable: this.state.JudgmentVariableID != null ? this.state.JudgmentVariable : '废弃',
              //       discardID: this.state.DraftNo == null ? null : array[0].ID,//草稿 启用废弃编号 获取id
              //     }, async () => {
              //       let parm = {
              //         Guid: ListGUID.StandingBook,  //变更申请
              //         ItemId: array[0].ID,
              //         Obj: {
              //           Title: this.state.form.contract, //合同编号
              //           AcceptTime: this.state.form.date == null ? null : this.state.form.date,//法务受理日
              //           Language: this.state.form.language,//语言
              //           Problem: this.state.form.problem,//问题id
              //           Contractualproblems: this.Ergodicvalue(this.state.problemList, this.state.form.problem),//问题
              //           LastAnswerTime: this.state.form.date1 == null ? null : this.state.form.date1,//法务最后回答
              //           ContractNatureID: this.state.form.nature,//合同性质id
              //           ContractNature: this.Ergodicvalue(this.state.natureList, this.state.form.nature),//合同性质
              //           ContractName: this.state.form.theContract,//合同名称
              //           ContractDeadlineID: this.state.form.term,//合同期限id
              //           ContractDeadline: this.Ergodicvalue(this.state.termList, this.state.form.term),//合同期限
              //           Keyword1: this.state.form.keywords1,//关键1
              //           ContractSignificanceID: this.state.form.importance,//合同重要性id
              //           ContractSignificance: this.Ergodicvalue(this.state.importanceList, this.state.form.importance),//合同重要性
              //           Keyword2: this.state.form.keywords2,//关键2
              //           ContactEditNature: this.state.form.modification.length > 0 ? this.state.form.modification.join(';') : '',//合同修改性质
              //           Our: this.state.form.we, //我方
              //           Qualifications: this.state.form.qualifications,//资质
              //           Counterparty: this.state.form.otherSide,//相对方
              //           LawyerReviewID: this.state.form.examination,//律师审查id
              //           ContractLawyerReview: this.Ergodicvalue(this.state.LawyerList, this.state.form.examination),//律师审查
              //           RelierName: this.state.form.community,//社内依赖者
              //           BelongsCompany: this.state.form.company,//所属公司
              //           ReviewOnID: this.state.form.reviewOnxuans,//审查担当
              //           BelongsDepartment: this.state.form.department,//所属部门
              //           FileAddress: this.state.form.file,//文件保存路径
              //           Other: this.state.form.other,//其它 
              //           HasReviewOpinion: this.state.form.proposal,//申请书
              //           // 有效、草稿、废弃
              //           ContractStatus: '有效',//合同状态
              //           AcceptYear: this.state.form.date == null ? null : Number(this.state.form.date.substring(0, 4)),//受理日年份
              //           //流水号
              //           SerialNum: this.state.form.contract == '' || this.state.form.contract == null ? null : Number(this.state.form.contract.substring(0, this.state.form.contract.lastIndexOf('-')).substr(-3)),
              //           VersionNum: 0,
              //           Names: this.state.form.enclosurelist.length == 0 ? null : this.state.form.enclosurelist.join(';'),
              //           AuthorId: this.state.AuthorId
              //           // AttObject:this.state.form.AttObject
              //         }
              //       }
              //       await Api._updateData(parm)
              //       parm.Obj['AuthorName'] = this.state.AuthorName;
              //       parm.Obj['ItemId'] = array[0].ID;
              //       await dynamicsService.UpdateContract(parm.Obj)
              //     })
              //     
              //   }, 300);
              // } else {
              //   let params: any = [
              //     {
              //       logic: "and",
              //       where: [
              //         {
              //           key: 'Our',
              //           filterType: "Eq",
              //           value: this.state.form.we
              //         },
              //         {
              //           key: 'AcceptYear',
              //           filterType: "Eq",
              //           value: this.state.form.date.substring(0, 4)
              //         },
              //         {
              //           key: 'ContractStatus',
              //           filterType: "Eq",
              //           value: '有效'
              //         },
              //         {
              //           key: 'VersionNum',
              //           filterType: "Eq",
              //           value: '0'
              //         }
              //       ]
              //     }
              //   ];
              //   let data = await Api._getPaged2({ Guid: ListGUID.StandingBook, PageSize: 100000, PageIndex: 1, FilterL: params })
              //   //取最大值 自增长
              //   // var param1 = {
              //   //   Guid: ListGUID.StandingBook, //台账
              //   // };
              //   // let Person = await Api._getPagedNext(param1);
              //   // 
              //   // 
              //   let Person = data.data
              //   if (Person.length != 0) {
              //     let array = []
              //     Person.forEach(element => {
              //       array.push({
              //         Title: Number(element.Title.substring(0, element.Title.lastIndexOf('-')).substr(-3)),
              //         ID: element.ItemId
              //       })
              //     });
              //     array.sort(function (a, b) {
              //       return a.Title - b.Title  //正序
              //     })
              //     
              //     let { form } = this.state;
              //     form.contract = this.state.form.we + this.state.form.date.substring(0, 4) + this.prefixZero(Number(array[array.length - 1].Title) + 1, 3) + '-0';
              //     await this.setState({
              //       form
              //     });
              //     this.props.form.setFieldsValue({
              //       contract: this.state.form.we + this.state.form.date.substring(0, 4) + this.prefixZero(Number(array[array.length - 1].Title) + 1, 3) + '-0'
              //     })
              //     setTimeout(async () => {
              //       form.file = this.state.form.date.substring(0, 4) + '/' + this.state.form.we + '/' + this.state.form.contract + '/';
              //       // form.file = '合同/'+this.state.form.we+'/'+this.state.form.date.substring(0,4)+'/'+this.state.form.contract;
              //       form.examination = 1
              //       form.proposal = '无'
              //       this.Folder(this.state.form.we, this.state.form.date.substring(0, 4), this.state.form.contract)
              //       this.setState({
              //         form,
              //         JudgmentVariable: this.state.JudgmentVariableID != null ? this.state.JudgmentVariable : '有效'
              //       }, async () => {
              //         // DraftNo 有值则代表需要更新当前数据 否则新增
              //         if (this.state.currentForm) {
              //           let parm = {
              //             Guid: ListGUID.StandingBook,  //变更申请
              //             ItemId: this.state.currentForm.ItemId,
              //             Obj: {
              //               Title: this.state.form.contract, //合同编号
              //               AcceptTime: this.state.form.date == null ? null : this.state.form.date,//法务受理日
              //               Language: this.state.form.language,//语言
              //               Problem: this.state.form.problem,//问题id
              //               Contractualproblems: this.Ergodicvalue(this.state.problemList, this.state.form.problem),//问题
              //               LastAnswerTime: this.state.form.date1 == null ? null : this.state.form.date1,//法务最后回答
              //               ContractNatureID: this.state.form.nature,//合同性质id
              //               ContractNature: this.Ergodicvalue(this.state.natureList, this.state.form.nature),//合同性质
              //               ContractName: this.state.form.theContract,//合同名称
              //               ContractDeadlineID: this.state.form.term,//合同期限id
              //               ContractDeadline: this.Ergodicvalue(this.state.termList, this.state.form.term),//合同期限
              //               Keyword1: this.state.form.keywords1,//关键1
              //               ContractSignificanceID: this.state.form.importance,//合同重要性id
              //               ContractSignificance: this.Ergodicvalue(this.state.importanceList, this.state.form.importance),//合同重要性
              //               Keyword2: this.state.form.keywords2,//关键2
              //               ContactEditNature: this.state.form.modification.length > 0 ? this.state.form.modification.join(';') : '',//合同修改性质
              //               Our: this.state.form.we, //我方
              //               Qualifications: this.state.form.qualifications,//资质
              //               Counterparty: this.state.form.otherSide,//相对方
              //               LawyerReviewID: this.state.form.examination,//律师审查id
              //               ContractLawyerReview: this.Ergodicvalue(this.state.LawyerList, this.state.form.examination),//律师审查
              //               RelierName: this.state.form.community,//社内依赖者
              //               BelongsCompany: this.state.form.company,//所属公司
              //               ReviewOnID: this.state.form.reviewOnxuans,//审查担当
              //               BelongsDepartment: this.state.form.department,//所属部门
              //               FileAddress: this.state.form.file,//文件保存路径
              //               Other: this.state.form.other,//其它 
              //               HasReviewOpinion: this.state.form.proposal,//申请书
              //               // 有效、草稿、废弃
              //               ContractStatus: '有效',//合同状态
              //               AcceptYear: this.state.form.date == null ? null : Number(this.state.form.date.substring(0, 4)),//受理日年份
              //               //流水号
              //               SerialNum: this.state.form.contract == '' || this.state.form.contract == null ? null : Number(this.state.form.contract.substring(0, this.state.form.contract.lastIndexOf('-')).substr(-3)),
              //               VersionNum: 0,
              //               Names: this.state.form.enclosurelist.length == 0 ? null : this.state.form.enclosurelist.join(';'),
              //               AuthorId: this.state.AuthorId
              //               // AttObject:this.state.form.AttObject
              //             }
              //           }
              //           await Api._updateData(parm)
              //           parm.Obj['AuthorName'] = this.state.AuthorName;
              //           parm.Obj['ItemId'] = this.state.currentForm.ItemId
              //           await dynamicsService.UpdateContract(parm.Obj)
              //         } else {
              //           //创建合同编号
      
              //           let pa = {
              //             Guid: ListGUID.StandingBook,  //变更申请
              //             Obj: {
              //               Title: this.state.form.contract, //合同编号
              //               AcceptTime: this.state.form.date == null ? null : this.state.form.date,//法务受理日
              //               Language: this.state.form.language,//语言
              //               Problem: this.state.form.problem,//问题id
              //               Contractualproblems: this.Ergodicvalue(this.state.problemList, this.state.form.problem),//问题
              //               LastAnswerTime: this.state.form.date1 == null ? null : this.state.form.date1,//法务最后回答
              //               ContractNatureID: this.state.form.nature,//合同性质id
              //               ContractNature: this.Ergodicvalue(this.state.natureList, this.state.form.nature),//合同性质
              //               ContractName: this.state.form.theContract,//合同名称
              //               ContractDeadlineID: this.state.form.term,//合同期限id
              //               ContractDeadline: this.Ergodicvalue(this.state.termList, this.state.form.term),//合同期限
              //               Keyword1: this.state.form.keywords1,//关键1
              //               ContractSignificanceID: this.state.form.importance,//合同重要性id
              //               ContractSignificance: this.Ergodicvalue(this.state.importanceList, this.state.form.importance),//合同重要性
              //               Keyword2: this.state.form.keywords2,//关键2
              //               ContactEditNature: this.state.form.modification.length > 0 ? this.state.form.modification.join(';') : '',//合同修改性质
              //               Our: this.state.form.we, //我方
              //               Qualifications: this.state.form.qualifications,//资质
              //               Counterparty: this.state.form.otherSide,//相对方
              //               LawyerReviewID: this.state.form.examination,//律师审查id
              //               ContractLawyerReview: this.Ergodicvalue(this.state.LawyerList, this.state.form.examination),//律师审查
              //               RelierName: this.state.form.community,//社内依赖者
              //               BelongsCompany: this.state.form.company,//所属公司
              //               ReviewOnID: this.state.form.reviewOnxuans,//审查担当
              //               BelongsDepartment: this.state.form.department,//所属部门
              //               FileAddress: this.state.form.file,//文件保存路径
              //               Other: this.state.form.other,//其它 
              //               HasReviewOpinion: this.state.form.proposal,//申请书
              //               // 有效、草稿、废弃
              //               ContractStatus: '有效',//合同状态
              //               AcceptYear: this.state.form.date == null ? null : Number(this.state.form.date.substring(0, 4)),//受理日年份
              //               //流水号
              //               SerialNum: this.state.form.contract == '' || this.state.form.contract == null ? null : Number(this.state.form.contract.substring(0, this.state.form.contract.lastIndexOf('-')).substr(-3)),
              //               VersionNum: 0,
              //               Names: this.state.form.enclosurelist.length == 0 ? null : this.state.form.enclosurelist.join(';'),
      
              //             }
              //           };
              //           let UPdeta = await Api._saveaddDataGuid(pa);
              //           
              //           pa.Obj['AuthorId'] = this.state.AuthorId;
              //           pa.Obj['AuthorName'] = this.state.AuthorName;
              //           pa.Obj['ItemId'] = UPdeta.data.ID;
              //           await dynamicsService.AddContract(pa.Obj)
              //           this.setState({
              //             currentForm: pa.Obj
              //           })
              //         }
              //       })
      
      
              //     }, 300);
              //     return;
              //   } else {
              //     let { form } = this.state;
              //     form.contract = this.state.form.we + this.state.form.date.substring(0, 4) + '001-0';
              //     this.props.form.setFieldsValue({
              //       contract: this.state.form.we + this.state.form.date.substring(0, 4) + '001-0'
              //     })
              //     await this.setState({
              //       form
              //     });
              //     setTimeout(async () => {
              //       form.file = this.state.form.date.substring(0, 4) + '/' + this.state.form.we + '/' + this.state.form.contract + '/';
              //       form.examination = 1
              //       form.proposal = '无'
              //       this.Folder(this.state.form.we, this.state.form.date.substring(0, 4), this.state.form.contract)
              //       this.setState({
              //         form,
              //         JudgmentVariable: this.state.JudgmentVariableID != null ? this.state.JudgmentVariable : '有效'
              //       })
              //       // if (this.state.DraftNo != null) return;
              //       if (this.state.currentForm) {
              //         let parm = {
              //           Guid: ListGUID.StandingBook,  //变更申请
              //           ItemId: this.state.currentForm.ItemId,
              //           Obj: {
              //             Title: this.state.form.contract, //合同编号
              //             AcceptTime: this.state.form.date == null ? null : this.state.form.date,//法务受理日
              //             Language: this.state.form.language,//语言
              //             Problem: this.state.form.problem,//问题id
              //             Contractualproblems: this.Ergodicvalue(this.state.problemList, this.state.form.problem),//问题
              //             LastAnswerTime: this.state.form.date1 == null ? null : this.state.form.date1,//法务最后回答
              //             ContractNatureID: this.state.form.nature,//合同性质id
              //             ContractNature: this.Ergodicvalue(this.state.natureList, this.state.form.nature),//合同性质
              //             ContractName: this.state.form.theContract,//合同名称
              //             ContractDeadlineID: this.state.form.term,//合同期限id
              //             ContractDeadline: this.Ergodicvalue(this.state.termList, this.state.form.term),//合同期限
              //             Keyword1: this.state.form.keywords1,//关键1
              //             ContractSignificanceID: this.state.form.importance,//合同重要性id
              //             ContractSignificance: this.Ergodicvalue(this.state.importanceList, this.state.form.importance),//合同重要性
              //             Keyword2: this.state.form.keywords2,//关键2
              //             ContactEditNature: this.state.form.modification.length > 0 ? this.state.form.modification.join(';') : '',//合同修改性质
              //             Our: this.state.form.we, //我方
              //             Qualifications: this.state.form.qualifications,//资质
              //             Counterparty: this.state.form.otherSide,//相对方
              //             LawyerReviewID: this.state.form.examination,//律师审查id
              //             ContractLawyerReview: this.Ergodicvalue(this.state.LawyerList, this.state.form.examination),//律师审查
              //             RelierName: this.state.form.community,//社内依赖者
              //             BelongsCompany: this.state.form.company,//所属公司
              //             ReviewOnID: this.state.form.reviewOnxuans,//审查担当
              //             BelongsDepartment: this.state.form.department,//所属部门
              //             FileAddress: this.state.form.file,//文件保存路径
              //             Other: this.state.form.other,//其它 
              //             HasReviewOpinion: this.state.form.proposal,//申请书
              //             // 有效、草稿、废弃
              //             ContractStatus: '有效',//合同状态
              //             AcceptYear: this.state.form.date == null ? null : Number(this.state.form.date.substring(0, 4)),//受理日年份
              //             //流水号
              //             SerialNum: this.state.form.contract == '' || this.state.form.contract == null ? null : Number(this.state.form.contract.substring(0, this.state.form.contract.lastIndexOf('-')).substr(-3)),
              //             VersionNum: 0,
              //             Names: this.state.form.enclosurelist.length == 0 ? null : this.state.form.enclosurelist.join(';'),
              //             AuthorId: this.state.AuthorId
              //             // AttObject:this.state.form.AttObject
              //           }
              //         }
              //         await Api._updateData(parm)
              //         parm.Obj['AuthorName'] = this.state.AuthorName;
              //         parm.Obj['ItemId'] = this.state.currentForm.ItemId
              //         await dynamicsService.UpdateContract(parm.Obj)
              //       } else {
              //         let pa = {
              //           Guid: ListGUID.StandingBook,  //变更申请
              //           Obj: {
              //             Title: this.state.form.contract, //合同编号
              //               AcceptTime: this.state.form.date == null ? null : this.state.form.date,//法务受理日
              //               Language: this.state.form.language,//语言
              //               Problem: this.state.form.problem,//问题id
              //               Contractualproblems: this.Ergodicvalue(this.state.problemList, this.state.form.problem),//问题
              //               LastAnswerTime: this.state.form.date1 == null ? null : this.state.form.date1,//法务最后回答
              //               ContractNatureID: this.state.form.nature,//合同性质id
              //               ContractNature: this.Ergodicvalue(this.state.natureList, this.state.form.nature),//合同性质
              //               ContractName: this.state.form.theContract,//合同名称
              //               ContractDeadlineID: this.state.form.term,//合同期限id
              //               ContractDeadline: this.Ergodicvalue(this.state.termList, this.state.form.term),//合同期限
              //               Keyword1: this.state.form.keywords1,//关键1
              //               ContractSignificanceID: this.state.form.importance,//合同重要性id
              //               ContractSignificance: this.Ergodicvalue(this.state.importanceList, this.state.form.importance),//合同重要性
              //               Keyword2: this.state.form.keywords2,//关键2
              //               ContactEditNature: this.state.form.modification.length > 0 ? this.state.form.modification.join(';') : '',//合同修改性质
              //               Our: this.state.form.we, //我方
              //               Qualifications: this.state.form.qualifications,//资质
              //               Counterparty: this.state.form.otherSide,//相对方
              //               LawyerReviewID: this.state.form.examination,//律师审查id
              //               ContractLawyerReview: this.Ergodicvalue(this.state.LawyerList, this.state.form.examination),//律师审查
              //               RelierName: this.state.form.community,//社内依赖者
              //               BelongsCompany: this.state.form.company,//所属公司
              //               ReviewOnID: this.state.form.reviewOnxuans,//审查担当
              //               BelongsDepartment: this.state.form.department,//所属部门
              //               FileAddress: this.state.form.file,//文件保存路径
              //               Other: this.state.form.other,//其它 
              //               HasReviewOpinion: this.state.form.proposal,//申请书
              //               // 有效、草稿、废弃
              //               ContractStatus: '有效',//合同状态
              //               AcceptYear: this.state.form.date == null ? null : Number(this.state.form.date.substring(0, 4)),//受理日年份
              //               //流水号
              //               SerialNum: this.state.form.contract == '' || this.state.form.contract == null ? null : Number(this.state.form.contract.substring(0, this.state.form.contract.lastIndexOf('-')).substr(-3)),
              //               VersionNum: 0,
              //               Names: this.state.form.enclosurelist.length == 0 ? null : this.state.form.enclosurelist.join(';'),
              //           }
              //         };
              //         
              //         
              //         let result = await Api._saveaddDataGuid(pa);
              //         pa.Obj['AuthorId'] = this.state.AuthorId;
              //         pa.Obj['AuthorName'] = this.state.AuthorName;
              //         pa.Obj['ItemId'] = result.data.ID;
              //         await dynamicsService.AddContract(pa.Obj)
              //         this.setState({
              //           currentForm: result.Obj
              //         })
              //       }
      
              //     }, 300);
              //   }
      
              // }
            }
          });
        })
    
    


  }
  //三位数 不足 补0
  public prefixZero(n, m) {
    var _a = (Array(m).join('0') + n).slice(-m);
    return _a;
  }
  //创建文件夹
  public async Folder(A, B, C) {
    let Persons2 = await Api.checkAndCreateFolder(`${ListGUID.ContractLibRelativeUrl}/${B}`)
    let Persons3 = await Api.checkAndCreateFolder(`${ListGUID.ContractLibRelativeUrl}/${B}/${A}`)
    let Persons4 = await Api.checkAndCreateFolder(`${ListGUID.ContractLibRelativeUrl}/${B}/${A}/${C}`)
  }
  //根据编号获取 数据 更新
  public async getedit(item) {
    this.setState({
      loading: true
    })
    let params: any = [
      {
        logic: "and",
        where: [
          {
            key: 'Title',
            filterType: "Eq",
            value: item
          }
        ]
      }
    ];
    let data = await Api._getPaged2({ Guid: ListGUID.StandingBook, PageSize: 100000, PageIndex: 1, FilterL: params })
    // var param = {
    //   Guid: ListGUID.StandingBook, //
    //   Filter: `Title eq '${item}'`
    // };
    // let Persons = await Api._getModel(param);
    let Persons = data.data;
    // 
    let reviewOnxuan = []
    let reviewOn = []
    if (Persons[0] && Persons[0].ReviewOnID != null) {
      if (Persons[0].ReviewOnID.indexOf(';') != -1) {
        let arrays = Persons[0].ReviewOnID.split(';')
        for (let i = 0; arrays.length > i; i++) {
          reviewOnxuan.push(Number(arrays[i].split('#')[0]))
          reviewOn.push(arrays[i].split('#')[1])
        }
      } else {
        reviewOnxuan.push(Number(Persons[0].ReviewOnID.split('#')[0]))
        reviewOn.push(Persons[0].ReviewOnID.split('#')[1])
      }
    }
    
    await this.setState({
      form: {
        contract: Persons[0].Title, //合同编号
        date: Persons[0].AcceptTime == null ? null : moment(Persons[0].AcceptTime).format('YYYY/MM/DD'),//法务受理日
        language: Persons[0].Language,//语言
        problem: Persons[0].Problem,//问题
        date1: Persons[0].LastAnswerTime == null ? null : moment(Persons[0].LastAnswerTime).format('YYYY/MM/DD'),//法务最后回答
        nature: Persons[0].ContractNatureID,//合同性质
        theContract: Persons[0].ContractName,//合同名称
        term: Persons[0].ContractDeadlineID,//合同期限
        keywords1: Persons[0].Keyword1,//关键1
        importance: Persons[0].ContractSignificanceID,//合同重要性
        keywords2: Persons[0].Keyword2,//关键2
        modification: !Persons[0].ContactEditNature ? [] : Persons[0].ContactEditNature.split(';'),//合同修改性质
        we: Persons[0].Our, //我方
        qualifications: Persons[0].Qualifications,//资质
        otherSide: Persons[0].Counterparty,//相对方
        examination: Persons[0].LawyerReviewID,//律师审查 
        community: Persons[0].RelierName,//社内依赖者
        company: Persons[0].BelongsCompany,//所属公司
        reviewOnxuans: Persons[0].ReviewOnID,//审查担当
        department: Persons[0].BelongsDepartment,//所属部门
        file: Persons[0].FileAddress,//文件保存路径
        other: Persons[0].Other,//其它
        proposal: Persons[0].HasReviewOpinion,//申请书 
        reviewOnxuan: reviewOnxuan,
        reviewOn: reviewOn,
        enclosurelist: Persons[0].Names == null ? [] : Persons[0].Names.split(';'),
        cutNumber: Persons[0].RuleNumber
      },
      DraftNo: Persons[0].ContractStatus == '草稿' ? Persons[0].Title : null,
      JudgmentVariableID: Persons[0].ItemId,
      JudgmentVariable: Persons[0].ContractStatus == '有效' ? '废弃' : Persons[0].ContractStatus,
      wedisabled: Persons[0].ContractStatus == '草稿' ? false : true,
      time: Persons[0].AcceptYear,
      loading: false,
      currentForm: Persons[0]
    })
    
    this.props.form.setFieldsValue({
      contract: Persons[0].Title,
      date: Persons[0].AcceptTime == null ? null : moment(Persons[0].AcceptTime),
      date1: Persons[0].LastAnswerTime == null ? null : moment(Persons[0].LastAnswerTime),
      otherSide: Persons[0].Counterparty,
      text: Persons[0].Our,
      theContract: Persons[0].ContractName
    });
    await dynamicsService.UpdateListFileNames({dataid: Persons[0].id, listguid: ListGUID.StandingBook, fileaddress: Persons[0].FileAddress})

  }
  // 关闭按钮触发
  public async shutDown() {
    let MinistryJustice = await Api._isLegalDepartment();
    confirm({
      centered: true,
      title: '温馨提示',
      content: `是否关闭该页面,关闭该页面未提交数据清空?`,
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        // location.href = "#/Dashboard" 
        // 判断是否为法务部
        // MinistryJustice = false
        if (MinistryJustice) { location.href = "#/Dashboard" } else {
          location.href = "#/DocumentLibrary"
        }
      }
    });
  }

}
export default Form.create()(AddContractNo);